{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 4.33 s, sys: 532 ms, total: 4.86 s\n",
      "Wall time: 4.03 s\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "\n",
    "import malaya"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import tensorflow as tf\n",
    "\n",
    "class _LANG_MODEL:\n",
    "    def __init__(self, dimension = 32, output = 6):\n",
    "        self.X = tf.sparse_placeholder(tf.int32, name = 'X_Placeholder')\n",
    "        self.W = tf.sparse_placeholder(tf.int32, name = 'W_Placeholder')\n",
    "        self.Y = tf.placeholder(tf.int32, [None])\n",
    "        embeddings = tf.Variable(tf.truncated_normal([400_000, dimension]))\n",
    "        embed = tf.nn.embedding_lookup_sparse(\n",
    "            embeddings, self.X, self.W, combiner = 'mean'\n",
    "        )\n",
    "        self.logits = tf.layers.dense(embed, output)\n",
    "        self.logits = tf.identity(self.logits, name = 'logits')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From /Users/huseinzolkepli/Documents/tf-1.15/env/lib/python3.7/site-packages/tensorflow_core/python/ops/embedding_ops.py:515: div (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Deprecated in favor of operator or tf.math.divide.\n",
      "WARNING:tensorflow:From <ipython-input-2-7a1eb89e875a>:12: dense (from tensorflow.python.layers.core) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use keras.layers.Dense instead.\n",
      "WARNING:tensorflow:From /Users/huseinzolkepli/Documents/tf-1.15/env/lib/python3.7/site-packages/tensorflow_core/python/layers/core.py:187: Layer.apply (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `layer.__call__` method instead.\n",
      "INFO:tensorflow:Restoring parameters from /Users/huseinzolkepli/Malaya/language-detection/deep/model.ckpt\n"
     ]
    }
   ],
   "source": [
    "model = _LANG_MODEL()\n",
    "sess = tf.InteractiveSession()\n",
    "sess.run(tf.global_variables_initializer())\n",
    "saver = tf.train.Saver(tf.trainable_variables())\n",
    "saver.restore(sess, '/Users/huseinzolkepli/Malaya/language-detection/deep/model.ckpt')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[<tf.Variable 'Variable:0' shape=(400000, 32) dtype=float32_ref>,\n",
       " <tf.Variable 'dense/kernel:0' shape=(32, 6) dtype=float32_ref>,\n",
       " <tf.Variable 'dense/bias:0' shape=(6,) dtype=float32_ref>]"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "tf.trainable_variables()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'out/model.ckpt'"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "saver = tf.train.Saver(tf.trainable_variables())\n",
    "saver.save(sess, 'out/model.ckpt')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['X_Placeholder/shape',\n",
       " 'X_Placeholder/values',\n",
       " 'X_Placeholder/indices',\n",
       " 'W_Placeholder/shape',\n",
       " 'W_Placeholder/values',\n",
       " 'W_Placeholder/indices',\n",
       " 'Placeholder',\n",
       " 'Variable',\n",
       " 'dense/kernel',\n",
       " 'dense/bias',\n",
       " 'logits']"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "strings = ','.join(\n",
    "    [\n",
    "        n.name\n",
    "        for n in tf.get_default_graph().as_graph_def().node\n",
    "        if ('Variable' in n.op\n",
    "        or 'Placeholder' in n.name\n",
    "        or 'logits' in n.name\n",
    "        or 'alphas' in n.name\n",
    "        or 'self/Softmax' in n.name)\n",
    "        and 'adam' not in n.name\n",
    "        and 'beta' not in n.name\n",
    "        and 'global_step' not in n.name\n",
    "    ]\n",
    ")\n",
    "strings.split(',')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "def freeze_graph(model_dir, output_node_names):\n",
    "\n",
    "    if not tf.gfile.Exists(model_dir):\n",
    "        raise AssertionError(\n",
    "            \"Export directory doesn't exists. Please specify an export \"\n",
    "            'directory: %s' % model_dir\n",
    "        )\n",
    "\n",
    "    checkpoint = tf.train.get_checkpoint_state(model_dir)\n",
    "    input_checkpoint = checkpoint.model_checkpoint_path\n",
    "\n",
    "    absolute_model_dir = '/'.join(input_checkpoint.split('/')[:-1])\n",
    "    output_graph = absolute_model_dir + '/frozen_model.pb'\n",
    "    clear_devices = True\n",
    "    with tf.Session(graph = tf.Graph()) as sess:\n",
    "        saver = tf.train.import_meta_graph(\n",
    "            input_checkpoint + '.meta', clear_devices = clear_devices\n",
    "        )\n",
    "        saver.restore(sess, input_checkpoint)\n",
    "        output_graph_def = tf.graph_util.convert_variables_to_constants(\n",
    "            sess,\n",
    "            tf.get_default_graph().as_graph_def(),\n",
    "            output_node_names.split(','),\n",
    "        )\n",
    "        with tf.gfile.GFile(output_graph, 'wb') as f:\n",
    "            f.write(output_graph_def.SerializeToString())\n",
    "        print('%d ops in the final graph.' % len(output_graph_def.node))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "INFO:tensorflow:Restoring parameters from out/model.ckpt\n",
      "WARNING:tensorflow:From <ipython-input-7-9a7215a4e58a>:23: convert_variables_to_constants (from tensorflow.python.framework.graph_util_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use `tf.compat.v1.graph_util.convert_variables_to_constants`\n",
      "WARNING:tensorflow:From /Users/huseinzolkepli/Documents/tf-1.15/env/lib/python3.7/site-packages/tensorflow_core/python/framework/graph_util_impl.py:277: extract_sub_graph (from tensorflow.python.framework.graph_util_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use `tf.compat.v1.graph_util.extract_sub_graph`\n",
      "INFO:tensorflow:Froze 3 variables.\n",
      "INFO:tensorflow:Converted 3 variables to const ops.\n",
      "43 ops in the final graph.\n"
     ]
    }
   ],
   "source": [
    "freeze_graph('out', strings)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "def load_graph(frozen_graph_filename):\n",
    "    with tf.gfile.GFile(frozen_graph_filename, 'rb') as f:\n",
    "        graph_def = tf.GraphDef()\n",
    "        graph_def.ParseFromString(f.read())\n",
    "    with tf.Graph().as_default() as graph:\n",
    "        tf.import_graph_def(graph_def)\n",
    "    return graph"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "g = load_graph('out/frozen_model.pb')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "input_nodes = ['X_Placeholder/shape',\n",
    " 'X_Placeholder/values',\n",
    " 'X_Placeholder/indices',\n",
    " 'W_Placeholder/shape',\n",
    " 'W_Placeholder/values',\n",
    " 'W_Placeholder/indices']\n",
    "output_nodes = ['logits']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "input_nodes = {label: g.get_tensor_by_name(f'import/{label}:0') for label in input_nodes}\n",
    "output_nodes = {label: g.get_tensor_by_name(f'import/{label}:0') for label in output_nodes}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "({'X_Placeholder/shape': <tf.Tensor 'import/X_Placeholder/shape:0' shape=(?,) dtype=int64>,\n",
       "  'X_Placeholder/values': <tf.Tensor 'import/X_Placeholder/values:0' shape=(?,) dtype=int32>,\n",
       "  'X_Placeholder/indices': <tf.Tensor 'import/X_Placeholder/indices:0' shape=(?, ?) dtype=int64>,\n",
       "  'W_Placeholder/shape': <tf.Tensor 'import/W_Placeholder/shape:0' shape=(?,) dtype=int64>,\n",
       "  'W_Placeholder/values': <tf.Tensor 'import/W_Placeholder/values:0' shape=(?,) dtype=int32>,\n",
       "  'W_Placeholder/indices': <tf.Tensor 'import/W_Placeholder/indices:0' shape=(?, ?) dtype=int64>},\n",
       " {'logits': <tf.Tensor 'import/logits:0' shape=(?, 6) dtype=float32>})"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "input_nodes, output_nodes"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "test_sess = tf.Session(graph = g)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "INFO:tensorflow:Restoring parameters from /Users/huseinzolkepli/Malaya/language-detection/deep/model.ckpt\n"
     ]
    }
   ],
   "source": [
    "deep = malaya.language_detection.deep_model()\n",
    "chinese_text = '今天是６月１８号，也是Muiriel的生日！'\n",
    "from malaya.text.function import language_detection_textcleaning\n",
    "strings = [language_detection_textcleaning(i) for i in [chinese_text]]\n",
    "subs = [\n",
    "    ' '.join(s)\n",
    "    for s in deep._bpe.encode(strings, output_type = deep._type)\n",
    "]\n",
    "transformed = deep._vectorizer.transform(subs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "coo = transformed.tocoo()\n",
    "indices = np.array([coo.row, coo.col]).transpose()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 678 ms, sys: 327 ms, total: 1 s\n",
      "Wall time: 1.02 s\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "(1, 6)"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "o = test_sess.run(output_nodes['logits'],\n",
    "        feed_dict = {input_nodes['X_Placeholder/shape']: coo.shape,\n",
    "                    input_nodes['X_Placeholder/values']: coo.col,\n",
    "                    input_nodes['X_Placeholder/indices']: indices,\n",
    "                    input_nodes['W_Placeholder/shape']: coo.shape,\n",
    "                    input_nodes['W_Placeholder/values']: coo.data,\n",
    "                    input_nodes['W_Placeholder/indices']: indices})\n",
    "o.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensorflow.tools.graph_transforms import TransformGraph"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "transforms = ['add_default_attributes',\n",
    "             'remove_nodes(op=Identity, op=CheckNumerics, op=Dropout)',\n",
    "             'fold_batch_norms',\n",
    "             'fold_old_batch_norms',\n",
    "             'quantize_weights(fallback_min=-10, fallback_max=10)',\n",
    "             'strip_unused_nodes',\n",
    "             'sort_by_execution_order']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [],
   "source": [
    "input_nodes = ['X_Placeholder/shape',\n",
    " 'X_Placeholder/values',\n",
    " 'X_Placeholder/indices',\n",
    " 'W_Placeholder/shape',\n",
    " 'W_Placeholder/values',\n",
    " 'W_Placeholder/indices']\n",
    "output_nodes = ['logits']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From <ipython-input-21-67774558feef>:4: FastGFile.__init__ (from tensorflow.python.platform.gfile) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use tf.gfile.GFile.\n"
     ]
    }
   ],
   "source": [
    "pb = 'out/frozen_model.pb'\n",
    "\n",
    "input_graph_def = tf.GraphDef()\n",
    "with tf.gfile.FastGFile(pb, 'rb') as f:\n",
    "    input_graph_def.ParseFromString(f.read())\n",
    "        \n",
    "transformed_graph_def = TransformGraph(input_graph_def, \n",
    "                                       input_nodes,\n",
    "                                       output_nodes, transforms)\n",
    "\n",
    "with tf.gfile.GFile(f'{pb}.quantized', 'wb') as f:\n",
    "    f.write(transformed_graph_def.SerializeToString())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
